﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MarkDownFileSplitter.AIAnalaysis
{
    internal class OllamaUtils
    {
        public static string SummarizeContentOfLevel3(List<string> content)
        {
            // 修正拼写错误 "messsage" -> "message"
            string message = $"请用40字以内总结出下面文字的概要内容：{string.Join("\n", content)}";
            return SendChatRequest(message);
        }

        public static string SendChatRequest(string userMessage)
        {
            var url = GlobalSetting.Instance.OllamaUlr + "/api/generate";
            var modelName = GlobalSetting.Instance.OllamaModelName;
            using (HttpClient client = new HttpClient())
            {
                var requestBody = new
                {
                    model = modelName,
                    prompt = userMessage,
                    stream = false,
                    options = new
                    {
                        temperature = 0.7,
                        max_tokens = 2000
                    }
                };

                var content = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");
                var response = client.PostAsync(url, content).Result;

                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception($"HTTP error! status: {response.StatusCode}");
                }

                var jsonResponse = response.Content.ReadAsStringAsync().Result;
                dynamic result = JsonConvert.DeserializeObject(jsonResponse);
                return result.response;
            }
        }
    }
}
